<template>
  <div v-loading="state.loading">
    <div class="opts">
      <div class="opt-item">
        <label for="">观测间隔</label>
        <input type="number" v-model="state.step" />
      </div>
      <div class="opt-item">
        <label for="">最低高度</label>
        <input type="number" v-model="state.minHeight" :min="0" />
      </div>
      <div class="opt-item">
        <label for="">最高高度</label>
        <input type="number" v-model="state.maxHeight" :min="state.minHeight" />
      </div>
      <div class="opt-item">
        <label for="">时间范围</label>
        <el-time-picker v-model="state.times" is-range range-separator="To" start-placeholder="起始时间" end-placeholder="结束时间" />
      </div>
      <div class="opt-item">
        <label for="">时间分钟</label>
        <input type="number" v-model="state.timeInterval" />
      </div>
    </div>
    <ColorMap />
    <div class="btns">
      <button class="btn" @click="startAnalyse">分析</button>
      <button class="btn" @click="clean">清除</button>
    </div>
  </div>
</template>

<script setup>
  import { onBeforeUnmount, computed, reactive, toRaw } from 'vue';
  import * as Cesium from 'cesium';
  import useDraw, { DrawType } from '@/hooks/useDraw';
  import ColorMap from '@/components/ColoMap.vue';
  import { ElNotification } from 'element-plus';
  import { vLoading, ElTimePicker } from 'element-plus';
  import { ShadowsAnalysis } from 'cgak';
  import { colorByPCT } from '@/util/tool';

  const now = new Date();
  const date = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
  const state = reactive({
    tiped: false,
    loading: false,
    step: 10,
    minHeight: 20,
    maxHeight: 50,
    multiplier: 60 * 60 * 30,
    timeInterval: 30,
    times: [new Date(date + ' 8:00:00'), new Date(date + ' 17:00:00')],
  });
  const viewer = window.viewer;
  let shadows = undefined;

  const updateResolutionScale = viewer => {
    //判断是否支持图像渲染像素化处理
    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
      viewer.resolutionScale = window.devicePixelRatio;
    }
  };
  const showRateResult = result => {
    console.log(result);
    result.positions.forEach((p, i) => {
      const rate = p.rate * 100; // 阴影率，取值范围是0到1，0代表一直有光照，1代表一直无光照

      const e = viewer.entities.add({
        position: p,
        point: {
          pixelSize: 6,
          color: colorByPCT(rate),
        },
      });
      e.customProperty = Number.parseInt(100 - rate);
    });
  };

  const prepared = () => {
    updateResolutionScale(viewer);
    viewer.scene.skyBox.show = false;
    viewer.shadows = true;
    viewer.scene.requestRenderMode = false;
    const s = toRaw(state.times[0]);
    const e = toRaw(state.times[1]);
    // const s = new Date(date + ' 8:00:00');
    // const e = new Date(date + ' 10:00:00');
    viewer.clock.startTime = Cesium.JulianDate.fromDate(s);
    viewer.clock.stopTime = Cesium.JulianDate.fromDate(e);
    viewer.clock.currentTime = s;
    viewer.clock.multiplier = state.timeInterval * 60 * 1000;

    if (!shadows) {
      shadows = new ShadowsAnalysis(viewer, {
        darkness: 0.7, // 阴影透明度, 0-1，值越大越透明
        multiplier: state.timeInterval * 60 * 1000,
      });
      window.shadows = shadows;
    }
  };

  const { drawStart, drawStop, drawClear } = useDraw(window.viewer, {
    type: DrawType.POLYGON,
    finishCallback: async positions => {
      prepared();
      if (positions.length >= 3) {
        drawClear();
        console.log(toRaw(state.times[0]), toRaw(state.times[1]));
        const result = await shadows.analyse({
          // startDate: new Date(date + ' 8:00:00'),
          // endDate: new Date(date + ' 18:00:00'),
          startDate: toRaw(state.times[0]),
          endDate: toRaw(state.times[1]),
          positions: positions,
          step: state.step,
          minHeight: state.minHeight,
          maxHeight: state.maxHeight,
        });
        showRateResult(result);
        viewer.shadows = false;
      }
    },
  });

  const startAnalyse = () => {
    if (!state.tiped) {
      ElNotification({ message: '点击鼠标左键绘制视线，每两点分析一次，点击右键结束。', duration: 5000 });
      state.tiped = true;
    }
    drawStart();
  };

  const clean = () => {
    drawStop();
    drawClear();
    viewer.entities.removeAll();
  };

  onBeforeUnmount(() => {
    clean();
  });
</script>

<style lang="scss" scoped>
  .btns {
    margin: 2em 0em;
  }
</style>
